#include <iostream>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
class Client
{
public:
    Client(const string &ip, const uint16_t &port) : _fd(-1), _Sip(ip), _Sport(port) {}
    void init()
    {
        _fd = socket(AF_INET, SOCK_STREAM, 0);
        if (_fd == -1)
        {
            cerr << strerror(errno) << endl;
            exit(1);
        }
        cout << "socket success" << endl;
    }
    void run()
    {
        struct sockaddr_in addr;
        bzero(&addr, 0);
        addr.sin_family = AF_INET;
        addr.sin_addr.s_addr = inet_addr(_Sip.c_str());
        addr.sin_port = htons(_Sport);
        if (connect(_fd, (struct sockaddr *)&addr, sizeof(addr)) == -1)
        {
            cerr << strerror(errno) << endl;
            exit(2);
        }
        else
        {
            while (true)
            {
                string messages;
                cout << " please input#";
                getline(cin, messages);
                write(_fd, messages.c_str(), messages.size());
                char buffer[1024];
                int n = read(_fd, buffer, sizeof(buffer) - 1);
                if (n > 0)
                {
                    buffer[n] = 0;
                    cout << "[Server] : " << buffer << endl;
                }
                else
                    break;
            }
        }
    }
    ~Client()
    {
        close(_fd);
    }

private:
    int _fd;
    string _Sip;
    uint16_t _Sport;
};